package com.arsProfundis.dal.mongo

import com.mongodb.casbah._
import com.mongodb.DBObject
import com.mongodb.casbah.Imports._

import com.arsProfundis.model._
import com.arsProfundis.dal.mappers._

class PersonDao extends MongoAbstractDao[Person, String] {


	implicit protected val dbObject2DomainObjectMapper: (DBObject) => Either[Exception, Person] = PersonDao.dbObjectToPerson _
	implicit protected val domainObject2DbObjectMapper: (Person) => DBObject = PersonDao.personToDBObject _

}

object PersonDao {

	import com.arsProfundis.dal.mongo.mappings._
	import com.arsProfundis.dal.mongo.mappings.Properties._

	val Name = mondatoryProperty("name", Mapper.String)

	implicit def dbObjectToPerson(dbObject: DBObject): Either[Exception, Person] = {
		try {
			val id = dbObject.getAs[String]("_id").get
			Right(new Person(id, Name(dbObject)))
		} 
		catch {
			case e: Exception => Left(e)
		}
	}

	implicit def personToDBObject(person: Person): DBObject = {
		val ret = MongoDBObject("_id" -> person.id)     
		ret += Name(person.name)
		ret
	} 
}
